import axios from "axios";


const baseURL = process.env.VUE_APP_URL;
const headers = {
    "Content-Type": "application/json;charset=UTF-8",
};

let instance = axios.create({
    headers,
    baseURL: baseURL,
    timeout: 30000,
    withCredentials: true,
    transformResponse: [
        function (json) {

            json = instance.transformNumber(json);
            try {
                json = JSON.parse(json);
            } catch (e) {
                console.log("axios transformResponse:" + e.message);
            }
            return json;
        },
    ],
});

instance.transformNumber = (str) => {
    return str.replace(
        /("(?:\\u[\da-f]{4}|\\[\d\D]|[^\\"])*")|([^"]+)/gi, function ($, $1, $2) {
            if ($1) return $1;
            return $2.replace(/[\d\.-]{16,}/g, '"$&"');
        }
    );
};

const isEmptyObj = (obj) => {
    for (var key in obj) {
        return false;
    }
    return true;
};

//POST传参序列化
instance.interceptors.request.use(
    (request) => {
        //设置验证
        request.auth={
            username: 'test2',
            password: '2'
        }
        if (request.data instanceof FormData) {
            return request;
        }
        for (let i in request.params) {
            if (typeof request.params[i] == "string") {
                request.params[i] = request.params[i].trim();
            }
        }
        if (request.method === "get") {
            request.params = {
                ...request.params,
                _t: new Date().getTime(),
            };
        } else if (request.method === "post") {
            if (!isEmptyObj(request.params)) {
                request.params = {
                    ...request.params,
                    _t: new Date().getTime(),
                };
            }
            request.data = {
                ...request.data,
            };
        }
        return request;
    },
    (error) => {
        return Promise.reject(error);
    }
);

//返回状态判断

//需要返回lastModified参数的接口都要进白名单

var lastTime = new Date().getTime();

instance.interceptors.response.use(
    (res) => {
        //  console.log(res)
        if (res.status != 200) {
            // store.commit("logout");
            return res.data;
        }

        if (res.data) {
            return res.data;
        }
        return res;
    },
    (error) => {
        if (!error.response) {
            console.log("请求超时");
            return;
        }
        console.log(error.response);
        //404等问题可以在这里处理

        if (error.response.status >= 500) {
            var currTime = new Date().getTime();
            var diff = currTime - lastTime;
            lastTime = currTime;
            //console.log(diff)
            if (diff < 200) return;
            console.log("网络错误，请稍后再试");
        } else if (error.response.status >= 400) {
            console.log('网络异常');
        }
        return Promise.reject(error);
    }
);

export default instance;
